import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/student/assignmentSettings.dart';
import 'package:universal_html/html.dart' as uHtml;
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class MiniBookForWebWebview extends StatefulWidget {
  const MiniBookForWebWebview({
    Key? key,
    required this.bookId,
    this.bookCode,
    this.bookTitle,
    this.assignmentId,
    //required this.readingType,
    //this.userName,
  }) : super(key: key);
  final String bookId;
  final String? bookCode;
  final String? bookTitle;
  final String? assignmentId;
  //final String? userName;
  //final NanhaiBookReadingTypes readingType;
  static const String routeName = '/student/book';

  @override
  _MiniBookForWebWebviewState createState() => _MiniBookForWebWebviewState();
}

class _MiniBookForWebWebviewState extends State<MiniBookForWebWebview> {
  final GlobalKey webViewKey = GlobalKey();
  InAppWebViewController? webViewController;
  InAppWebViewSettings options = InAppWebViewSettings(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      useHybridComposition: true,
      allowsInlineMediaPlayback: true,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true,
      cacheEnabled: true,
      domStorageEnabled: true,
      javaScriptEnabled: true,
      allowsPictureInPictureMediaPlayback: true,
      enableViewportScale: true,
      disableLongPressContextMenuOnLinks: true,
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW);

  late PullToRefreshController pullToRefreshController;
  late ContextMenu contextMenu;

  final BooksController _booksController = Get.find();
  final box = Hive.box('appconfig');
  AssignmentSettings _assignmentSettingsDto = new AssignmentSettings();
  AssignmentSettings _profileSettingsDto = new AssignmentSettings();
  bool updateProgress = false;
  late Timer periodicTimer;
  ValueNotifier valueNotifier = ValueNotifier(false);
  bool isFinished = false;

  @override
  void initState() {
    super.initState();

    if (widget.bookId != '') {
      _booksController.setCurrentBookId(widget.bookId.toString());
    }

    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
            Constants.NanhaiRole_Student ||
        box.get(CacheManagerKey['nanhairole'].toString()) ==
            Constants.NanhaiRole_Individual) {
      updateProgress = true;
    }
    var settings = json.decode(
        box.get(CacheManagerKey['profilesettings'].toString()).toString());
    var _vocabulary = settings != null && settings['vocabulary'] != null
        ? settings['vocabulary']
        : true;
    if (widget.assignmentId != null && widget.assignmentId != '') {
      var assignmentSettings = _booksController.getCurrentAssignmentSettings();
      _assignmentSettingsDto.id = widget.assignmentId;
      if (assignmentSettings != null) {
        _assignmentSettingsDto.lang = assignmentSettings.lang;
        _assignmentSettingsDto.language = assignmentSettings.language;
        _assignmentSettingsDto.audio = assignmentSettings.audio;
        _assignmentSettingsDto.dictionary = assignmentSettings.dictionary;
        _assignmentSettingsDto.music = assignmentSettings.music;
        _assignmentSettingsDto.pinyin = assignmentSettings.pinyin;
        _assignmentSettingsDto.quizAudio = assignmentSettings.quizAudio;
      }
      uHtml.window.sessionStorage['assignmentId'] = '${widget.assignmentId}';
      uHtml.window.sessionStorage['assignmentSettings'] =
          '${assignmentSettingsToJson(_assignmentSettingsDto)}';
      uHtml.window.sessionStorage['vocabulary'] =
          _vocabulary ? 'true' : 'false';
    } else {
      uHtml.window.sessionStorage['assignmentId'] = '';
      uHtml.window.sessionStorage['assignmentSettings'] = '';
      _profileSettingsDto.lang = box.get('UserLang');
      _profileSettingsDto.language = box.get('UserLanguage');
      _profileSettingsDto.pinyin = box.get('UserPinyin');
      uHtml.window.sessionStorage['profileSettings'] =
          '${json.encode(_profileSettingsDto)}';
      uHtml.window.sessionStorage['vocabulary'] =
          _vocabulary ? 'true' : 'false';
    }

    pullToRefreshController = PullToRefreshController(
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    periodicTimer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    String _bookUrl = '${Constants.BaseURL}icr/student/book/${widget.bookId}';
    return Scaffold(
      resizeToAvoidBottomInset: true,
      // appBar: AppBar(
      //   title: Text(widget.bookTitle.toString()),
      // ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: Stack(
                children: [
                  InAppWebView(
                    key: webViewKey,
                    initialUrlRequest: URLRequest(url: WebUri(_bookUrl)),
                    initialSettings: options,
                    pullToRefreshController: pullToRefreshController,
                    onLoadStart: (controller, url) async {},
                    onWebViewCreated: (controller) async {
                      webViewController = controller;
                    },
                    onPermissionRequest: (controller, request) async {
                      return PermissionResponse(
                          resources: request.resources,
                          action: PermissionResponseAction.GRANT);
                    },
                    shouldOverrideUrlLoading:
                        (controller, navigationAction) async {
                      return NavigationActionPolicy.ALLOW;
                    },
                    onLoadStop: (controller, url) async {},
                    onReceivedError: (controller, request, error) {
                      pullToRefreshController.endRefreshing();
                    },
                    onProgressChanged: (controller, progress) {},
                    onUpdateVisitedHistory:
                        (controller, url, androidIsReload) {},
                    onConsoleMessage: (controller, consoleMessage) async {},
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
